package com.wxy.demo.controller;

import com.wxy.demo.core.AssertUtils;
import com.wxy.demo.core.IdDto;
import com.wxy.demo.core.PageResult;
import com.wxy.demo.core.QueryPage;
import com.wxy.demo.dao.UserDao;
import com.wxy.demo.entity.DataSourceInfo;
import com.wxy.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 *
 * </p>
 *
 * @author e-Xiaoyuan.Wang
 * @since 2022/4/12 9:42
 */
@Transactional
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserDao userDao;

    @PostMapping("/save")
    private Object save(@RequestBody User user) {
        AssertUtils.notBlank(user.getName(), "用户名称不能为空");
        User u = userDao.findByName(user.getName());
        AssertUtils.isTrue((user.getId() == null && u == null) ||
                        (user.getId() != null && Objects.equals(user.getId(), u.getId())),
                "用户不能重复");
        if (user.getStatus() == null) {
            user.setStatus(1);
        }
        return userDao.save(user);
    }

    @PostMapping("/lock")
    private Object lock(@RequestBody IdDto dto) {
        userDao.findById(dto.getId()).ifPresent(user -> {
            user.setStatus(Objects.equals(user.getStatus(), 1) ? 2 : 1);
            userDao.save(user);
        });
        return true;
    }

    @PostMapping("/deleteById")
    private Object deleteById(@RequestBody IdDto dto) {
        userDao.deleteById(dto.getId());
        return true;
    }

    @PostMapping("/findPage")
    private Object findPage(@RequestBody QueryPage<User> queryPage) {
        Pageable pageable = PageRequest.of(queryPage.getPageNum() - 1, queryPage.getPageSize(),
                Sort.by(Sort.Direction.DESC, "id"));
        User query = Optional.ofNullable(queryPage.getQueryModel()).orElse(new User());
        query.setStatus(null);
        ExampleMatcher matching = ExampleMatcher.matching().withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        return new PageResult<>(userDao.findAll(Example.of(query, matching), pageable));
    }
}
